import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/cookie.js';

const modules = import.meta.glob('./modules/*.js', {
  import: 'default',
  eager: true,
});
const routes = [];
// 遍历所有模块并打印它们的代码
for (const path in modules) {
  const module = modules[path];
  if (Array.isArray(module)) {
    routes.push(...module);
  } else {
    routes.push(module);
  }
}
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});
// 监听所有路由跳转
router.beforeEach((to, from, next) => {
  const token = getToken();
  if (!['/', '/login', '/register', '/forgetPassword'].includes(to.path) && !token) {
    ElMessage.error('登录后可以使用当前功能，请登录！');
    next({ path: '/login' })
  }
  next();
})

export default router;
